package cn.shop.crontab.message.impl;

import cn.shop.crontab.message.MessageUtil;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.OnExceptionContext;
import com.aliyun.openservices.ons.api.SendCallback;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author : 李一涵
 * @date : Created in 2022/5/28 14:58
 * @description :
 */
@Component
@ConditionalOnExpression("'${spring.profiles.active:dev}' == 'online'")
public class AliyunMessageUtil implements MessageUtil {

    private final static Logger LOG = LoggerFactory.getLogger(RocketMessageUtil.class);

    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private ProducerBean producer;

    @Override
    public <T> void sendMessage(String topic, String tag, T t) throws Exception {
        Message message = new Message();
        message.setTopic(topic);
        message.setTag(tag);
        message.setBody(objectMapper.writeValueAsBytes(t));
        send(message);
    }

    private void send(Message message) {
        LOG.info("发送阿里云消息：{}", message);
        producer.sendAsync(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                LOG.info("{}消息发送成功, 返回结果：{}", message, sendResult);
            }

            @Override
            public void onException(OnExceptionContext context) {
                LOG.warn("{}消息发送失败，错误信息:", message, context.getException());
            }
        });
    }

}
